import 'dart:async';

import 'package:flutter/cupertino.dart';
import 'package:flutter_icons/flutter_icons.dart';
import 'package:flutterlib/common/constants/constants.dart';
import 'package:flutterlib/common/localization/default_localizations.dart';
import 'package:flutterlib/common/utils/navigator_utils.dart';
import 'package:flutterlib/common/utils/toast.dart';
import 'package:flutterlib/common/utils/utils.dart';
import 'package:flutterlib/model/im/group_pojo.dart';
import 'package:flutterlib/model/interest/interest_bean.dart';
import 'package:flutterlib/pages/interest/viewmodel/interest_store.dart';
import 'package:flutterlib/widgets/intro/flutter_intro.dart';
import 'package:loading/indicator/ball_beat_indicator.dart';
import 'package:loading/loading.dart';
import 'package:mobx/mobx.dart';
import 'package:smart_select/smart_select.dart';
import 'package:sticky_headers/sticky_headers.dart';
import 'package:thrio/thrio.dart';
import 'features_header.dart';

class Page extends StatefulWidget {
  @override
  _PageState createState() => _PageState();
}

class _PageState extends State<Page> {
  String selectText = '';

  final InterestStore interestStore = InterestStore();
  final SettingsStore store =
      Provider.of<SettingsStore>(currentContext, listen: false);
  InterestBean _interest;
  GroupEntity _group;

  Intro intro = Intro(
    /// 总共的引导页数量，必传
    stepCount: 4,

    /// 高亮区域与 widget 的内边距
    padding: EdgeInsets.all(8),

    /// 高亮区域的圆角半径
    borderRadius: BorderRadius.all(Radius.circular(4)),

    /// 使用库默认提供的 useDefaultTheme 可以快速构建引导页
    /// 需要自定义引导页样式和内容，需要自己实现 widgetBuilder 方法
    widgetBuilder: StepWidgetBuilder.useDefaultTheme(
      /// 提示文本
      texts: [
        '这里可以动态和文章，和趣友们分享生活点滴',
        '这里可以发布兴趣图，把兴趣活动的精彩瞬间发布在这里吧',
        '这里可以招募到趣友到你专属的小圈中，可以在小圈里组织交流',
        '这里可以创建兴趣活动，只有自己的小圈的趣友可以看到和参加哦',
      ],
      buttonTextBuilder: (currPage, totalPage) {
        return currPage < totalPage - 1 ? '下一条' : '知道了';
      },
    ),
  );

  @override
  void initState() {
    super.initState();
    if (currentUser != null) {
      interestStore.fetchMyGroup(currentUser.uid);
    }
    var bool = SpUtils.getBool('show_select_intro', defValue: false);
    if(!bool) {
      Timer(Duration(microseconds: 0), () {
        intro.start(context);
        SpUtils.putBool('show_select_intro', true);
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(
          "选择",
          style: QuhuiConstant.smallText,
        ),
        leading: MyBackButton(),
        actions: [
          InkWell(
            onTap: () {
              if (selectText.isEmpty) {
                ToastUtils.toast(msg_select_morethanone);
                return;
              }
              if (selectText == send_post && _interest == null) {
                ToastUtils.toast(msg_select_interest);
                return;
              }
              if (selectText == send_card && _interest == null) {
                ToastUtils.toast(msg_select_interest);
                return;
              }
              if (selectText == send_activity && _group == null) {
                ToastUtils.toast(msg_select_group);
                return;
              }
              if (selectText == send_deploy_activity && _interest == null) {
                ToastUtils.toast(msg_select_interest);
                return;
              }

              if (selectText == send_post) {
                NavigatorUtils.goPostCreate(context, _interest.id);
              } else if (selectText == send_card) {
                NavigatorUtils.goCardCreate(context, _interest.id);
              } else if (selectText == send_deploy_activity) {
                NavigatorUtils.gotoDeployActivityCreate(context, _interest.id);
              } else if (selectText == send_activity) {
                NavigatorUtils.gotoActivityCreate(
                    context, _group.circleId, _group.interestId);
              }
            },
            child: Padding(
              padding: const EdgeInsets.all(8.0),
              child: Text(
                "下一步",
                style: QuhuiConstant.smallText,
              ),
            ),
          ),
        ],
      ),
      body: Scrollbar(
        child: ListView(
          addAutomaticKeepAlives: true,
          children: <Widget>[
            StickyHeader(
              header: const FeaturesHeader('动作'),
              content: Column(
                children: [
                  Row(
                    children: [
                      getButtonUI(send_post, selectText == send_post, 0),
                      getButtonUI(send_card, selectText == send_card, 1),
                    ],
                  ),
                  Row(
                    children: [
                      getButtonUI(send_deploy_activity,
                          selectText == send_deploy_activity, 2),
                      getButtonUI(send_activity, selectText == send_activity, 3),
                    ],
                  ),
                ],
              ),
            ),
            StickyHeader(
              header: const FeaturesHeader('发布位置'),
              content: Column(
                children: [
                  (selectText == send_post ||
                          selectText == send_card ||
                          selectText == send_deploy_activity)
                      ? Observer(builder: (_) {
                          List<InterestBean> result = store.interests;
                          if (result.length == 0) {
                            return Padding(
                              padding: const EdgeInsets.all(8.0),
                              child: Text(
                                "请先加入兴趣",
                                style: QuhuiConstant.smallText,
                              ),
                            );
                          }
                          var choice = result
                              .map((e) => S2Choice<InterestBean>(
                                  value: e, title: e.name))
                              .toList();
                          return SmartSelect<InterestBean>.single(
                            title: '选择兴趣',
                            value: _interest,
                            placeholder: '',
                            choiceItems: choice,
                            onChange: (state) =>
                                setState(() => _interest = state.value),
                            modalType: S2ModalType.bottomSheet,
                            modalFilter: true,
                            tileBuilder: (context, state) {
                              return S2Tile.fromState(
                                state,
                                isTwoLine: false,
                              );
                            },
                          );
                        })
                      : Container(),
                  selectText == send_activity
                      ? Observer(
                          builder: (_) {
                            var myGroupFuture = interestStore.myGroupFuture;
                            if (myGroupFuture.status ==
                                FutureStatus.fulfilled) {
                              List<GroupEntity> result = myGroupFuture.result;
                              if (result.length == 0) {
                                return Padding(
                                  padding: const EdgeInsets.all(8.0),
                                  child: Text(
                                    "请先加入小圈",
                                    style: QuhuiConstant.smallText,
                                  ),
                                );
                              }
                              var choice = result
                                  .map((e) => S2Choice<GroupEntity>(
                                      value: e, title: e.name))
                                  .toList();
                              return SmartSelect<GroupEntity>.single(
                                title: '选择小圈',
                                value: _group,
                                placeholder: '',
                                choiceItems: choice,
                                onChange: (state) =>
                                    setState(() => _group = state.value),
                                modalType: S2ModalType.bottomSheet,
                                modalFilter: true,
                                tileBuilder: (context, state) {
                                  return S2Tile.fromState(
                                    state,
                                    isTwoLine: false,
                                  );
                                },
                              );
                            } else if (myGroupFuture.status ==
                                FutureStatus.rejected) {
                              return Text(
                                "没有圈子数据",
                                style: QuhuiConstant.smallText,
                              );
                            } else {
                              return new Scaffold(
                                body: Container(
                                  color: QuhuiColors.white,
                                  child: Center(
                                    child: Loading(
                                        indicator: BallBeatIndicator(),
                                        size: 20.0,
                                        color: QuhuiColors.mainThemeColor),
                                  ),
                                ),
                              );
                            }
                          },
                        )
                      : Container(),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget getButtonUI(String txt, bool isSelected, introIndex) {
    return Padding(
      key: intro.keys[introIndex],
      padding: const EdgeInsets.all(8.0),
      child: Container(
        width: 100,
        height: 50,
        decoration: BoxDecoration(
            color: isSelected ? QuhuiColors.mainThemeColor : QuhuiColors.white,
            borderRadius: const BorderRadius.all(Radius.circular(24.0)),
            border: Border.all(color: QuhuiColors.mainThemeColor)),
        child: Material(
          color: Colors.transparent,
          child: InkWell(
            splashColor: Colors.white24,
            borderRadius: const BorderRadius.all(Radius.circular(24.0)),
            onTap: () {
              setState(() {
                selectText = txt;
              });
            },
            child: Padding(
              padding: const EdgeInsets.only(
                  top: 12, bottom: 12, left: 18, right: 18),
              child: Center(
                child: Text(
                  txt,
                  textAlign: TextAlign.left,
                  style: TextStyle(
                      fontWeight: FontWeight.w600,
                      fontSize: 12,
                      letterSpacing: 0.27,
                      color: isSelected
                          ? QuhuiColors.white
                          : QuhuiColors.mainThemeColor),
                ),
              ),
            ),
          ),
        ),
      ),
    );
  }
}
